package com.chalmerslosers.utils;


import java.util.List;
import java.util.HashMap;
import java.util.ArrayList;


public final class ParentPost {

        private Post parentPost;
        
        private List<ChildPost> children;
        
        public Post getPost(){
                return parentPost;
        }
        
        public List<ChildPost> getChildren(){
                return children;
        }
        
        public ParentPost( Post parent, List<Post> children ){
                
                this.parentPost = parent;
                
                // Build "child map", which maps a post ID to a list of immediate children
                HashMap<Long,List<Post>> childMap = new HashMap<Long,List<Post>>( 1+children.size() );
                                
                for( Post p : children )
                {
                        
                        List<Post> childList = childMap.get(p.getParentId());
                        if ( childList == null )
                        {
                                childList = new ArrayList<Post>(16);
                                childMap.put(p.getParentId(), childList );
                        }
                        
                        childList.add(p);
                }
                
                // use this to recursively traverse the hierarchy, and produce
                // an in-order flat list (with the right indentation)
                this.children = new ArrayList<ChildPost>( children.size() );
                buildChildList( parent, childMap, this.children, 1 );           
                
        }
        
        private void buildChildList( Post current, HashMap<Long,List<Post>> childMap, List<ChildPost> childList, int indentation ){
                                
                List<Post> nextPosts = childMap.get( current.getId());
                
                if ( nextPosts != null ){               
                        for( Post p : nextPosts ){
                                childList.add(new ChildPost(p, indentation));
                                buildChildList( p, childMap, childList, indentation+1);
                        }
                }               
        }
        
        
        public final class ChildPost{
                private Post post;
                private int indentation;
                public ChildPost( Post post, int indentation ){
                        this.post = post;
                        this.indentation = indentation;
                }
                
                public Post getPost(){
                        return post;
                }
                
                public int getIndentation(){
                        return indentation;
                }
        }
        
}
        